import {Component, forwardRef, OnInit} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {ConfigService} from '@kylin/config';

export const VERIFICATION_CODE_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => VerificationCodeComponent),
    multi: true
};

@Component({
    selector: 'kylin-verification-code',
    templateUrl: './verification-code.component.html',
    styleUrls: ['./verification-code.component.css'],
    providers: [VERIFICATION_CODE_VALUE_ACCESSOR]
})

export class VerificationCodeComponent implements OnInit, ControlValueAccessor {

    private deviceId = null;
    _validCode = null;
    _validCodeImgUrl = null;

    constructor(private configService: ConfigService) {
    }

    ngOnInit() {
        this.fetchValidCode();
    }

    validCodeChange($event) {
        this.propagateChange({deviceId: this.deviceId, validCode: this._validCode});
    }

    propagateChange = (data: any) => { // 相当于output功能,用于把改变的值传输出去

    };

    writeValue(value: any) { // 该方法用于将模型中的新值写入视图或 DOM 属性中
        this._validCode = value;
    }


    registerOnChange(fn: (data: any) => void): void {
        this.propagateChange = fn;
    }

    registerOnTouched(fn: any) {
    }

    fetchValidCode = () => {
        this.deviceId = this.generateNewDeviceId();
        this._validCodeImgUrl = `${this.configService.hostname}/validata/code/${this.deviceId}`;
    }

    generateNewDeviceId() {
        let d = new Date().getTime();
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
            const r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
    }
}
